
import {useEffect, useState} from 'react' 
import { useCountDown , useSessionStorageState } from 'ahooks';
import { history  } from 'umi'
import {Dialog} from 'antd-mobile'
import moment from 'moment'


// 自定义Hooks 
export const  useTimeDownCounter = (time=5000,interval=1000,onEnd=()=>{
    // history.push('/app')
})=>{
    const [targetDate, setTargetDate] = useState<number>();
    const [countdown] = useCountDown({
        targetDate: targetDate,
        onEnd,
        interval
    });

    useEffect(()=>{
        setTargetDate(Date.now() + time)
    },[])


    return [
        Math.round(countdown / interval)
    ]

}


export const useGotoPage = ()=>{


    const gotoPage = (url?:any)=>{
        history.push(url)
    }

    return [
        gotoPage
    ]
}



// 自定义Hooks 
export const useGetYearWeek = ()=>{
    //a为年 b为月 c为日
    /*  
        date1是当前日期  
        date2是当年第一天  
        d是当前日期是今年第多少天  
        用d + 当前年的第一天的周差距的和在除以7就是本年第几周  
    */
   
   const getWeek = ()=>{
       var time = new Date()
       var a = time.getFullYear()
       var b:any = time.getMonth() + 1;
       var c = time.getDate()
   
       var date1 = new Date(a, parseInt(b) - 1, c),
       date2 = new Date(a, 0, 1),
       d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
       return Math.ceil((d + (date2.getDay() + 1 - 1)) / 7);
   }

   return [
        getWeek
   ]

}



export const useCheckLogin = ()=>{
    const [appToken, setAppToken] = useSessionStorageState<string | undefined | any>(
        'appToken',  // key 
    )
    const hasLogin = (next:any)=>{
        if(appToken){
            next()
        }else{
            Dialog.confirm({
                content: '亲,你还没有登录,请先登录哦!!!',
                onConfirm: () => {
                    history.push("/login")
                },
            })
        }
    }

    return [
        hasLogin
    ]
}


export const useLoginAuthPush = ()=>{
    const loginAuthPush = ()=>{
        // 判断 登录成功改怎么跳转 
        // 登录成功全部跳转个人中心  
        // reg  findpass changepass mine
        // 其他 go(-1)
        var frompath = localStorage.getItem('frompath')
        if(frompath=='/reg' || frompath=='/changepass'  || frompath=='/findpass' ){
            history.push('/app/mine')
            console.log('go mine ')
        }else{
            history.go(-1)
            console.log('go -1 ')
        }
    }
    return [
        loginAuthPush
    ]
}


export const useCommon = ()=>{
    const setdateFormat = (time?:any,type='YYYY-MM-DD')=>{
        return moment(time).format(type)
    }

    return [
        setdateFormat
    ]
} 